package presentation.frame;

import java.rmi.RemoteException;

import javax.swing.JOptionPane;

import bl.service.AccountService;

import presentation.frame.DialogEvent;
import rmiClient.Client;
import data.entity.BLToViewMessage;
import data.entity.UserEntity;

public class LoginController {
	private LoginFrame frame;
	private Client c;
	
	public LoginController(){
		frame=new LoginFrame();
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
	}
	
	public UserEntity getUserEntity() {
		while (true) {
			try {
				Thread.sleep(50);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			DialogEvent event = frame.getEvent();
			if (event == null) {
				continue;
			}
			if (event == DialogEvent.CANCEL) {
				return null;
			}
			if(event==DialogEvent.REGISTER){
				disposeFrame();
				RegisterFrame frame=new RegisterFrame();
				frame.register();
			}
			if (event == DialogEvent.CONFIRM) {
				UserEntity ue=requireLogin(frame.getUserEntity());
				if(ue!=null){
					return ue;
				}else{
					continue;
				}
			}
		}
	}

	public void disposeFrame() {
		frame.dispose();
	}

	
	public static void main(String[]args){
		LoginController controller = new LoginController();
		UserEntity ue=controller.getUserEntity();

		if(ue!=null){

		try {
			new Frame(ue);
			Frame.addPane(new MainPane(ue));
		} catch (RemoteException e) {
			e.printStackTrace();
		}}
		//System.out.println(ue.getName());
	}
	
	public UserEntity requireLogin(UserEntity e){
		String name=e.getName();
		try {

			Client test = new Client();
			AccountService acs=test.getAccountService();

			BLToViewMessage message=acs.login(e.getName(), e.getPassWord());
			if(message==BLToViewMessage.NOT_EXIST){
				showUserNotExistMessage();
			}else if(message==BLToViewMessage.LOGIN_FAIL){
				showLoginFailMessage();
			}else if(message==BLToViewMessage.LOGIN_SUCCESS){
				UserEntity ue=acs.getUser(name);
				disposeFrame();
				return ue;
			}
		} catch (RemoteException e1) {
			e1.printStackTrace();
		}
		return null;
	}
	
	public void showUserNotExistMessage(){
		frame.stateLabel.setText("User Not Exist.");
		return;
	}
	
	public void showLoginFailMessage(){
		JOptionPane.showMessageDialog(null,"!");
		frame.stateLabel.setText("Login Fail.");
		return;
	}
}
